<template>
  <div>
    <Upload :action="resolveURL()"
            :multiple="true"
            :data="handleUploadData"
            :headers="headers"
            @change="handleChange"
            @preview="downloadClick"
            :remove="handleFileRemove"
            :beforeUpload="FileBeforeUpload"
            :fileList="fileList"
            :disabled="isQuery"
            :showUploadList="showUploadList"
            :bucketName="bucketName"
            :systemName="systemName"
            :markText="markText"
            :listType="listType"
            :fileSize="fileSize"
            :limit="limit"
            :accept="accept">
      <Button v-if="!isQuery">
        <Icon type="upload" /> 文件上传
      </Button>
    </Upload>
  </div>

</template>
<script>
import { storage } from '@zh/common-utils/http'
import { Upload, Button, Icon, message, Modal } from 'ant-design-vue'
import { getFileList, saveFile, deleteFile } from '../api/upload'
import { getFileInfoList } from './../api/file.js'
export default {
  name: 'ZFileUploader',
  components: {
    Upload,
    Button,
    Icon
  },
  props: {
    accept: {
      type: String,
      default: ''
    },
    value: {
      type: Array,
      default: () => new Array(),
      description: '附件列表默认值'
    },
    isQuery: {
      type: Boolean,
      default: false,
      description: '当值为true时表示只读'
    },
    configGroup: {
      type: String,
      default: '',
      description: '附件组'
    },
    showUploadList: {
      type: Boolean,
      default: true,
      description: '当值为true时表示显示当前的附件列表'
    },
    listType: {
      type: String,
      default: 'text',
      description:
        '上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card'
    },
    parentId: {
      type: String,
      default: null,
      description: '业务ID必填'
    },
    limit: {
      type: Number,
      default: 2,
      description: '上传限制数量'
    },
    fileSize: {
      type: Number,
      default: 200,
      description: '文件大小'
    },
    bucketName: {
      type: String,
      default: 'zongheng',
      description: '当前归属系统所在的空间名称'
    },
    systemName: {
      type: String,
      default: 'zongheng',
      description: '归属系统名称'
    },
    markText: {
      type: String,
      default: 'markText',
      description: '备注当前附件说明'
    },
    headers: {
      type: Object | String | Number | Array,
      default: null
    },
    handleRemove: {
      type: Function,
      default: null
    },
    beforeUpload: {
      type: Function,
      default: null,
      description: '上传前'
    },
    beforeDownload: {
      type: Function,
      default: null,
      description: '下载前'
    }
  },
  data () {
    return {
      fileList: [],
      flag: true
    }
  },
  watch: {
    parentId () {
      this.getFileList()
    },
    value: {
      handler (value) {
        if (this.parentId) {
          return
        }
        if (value.length > 0 && value[0] && !value[0].uid) {
          this.getFileInfoListFun(value)
          return
        }
        if (value) {
          this.fileList = value
        }
      },
      immediate: true,
      deep: true
    }
  },
  created () {
    if (this.parentId) {
      this.getFileList()
    }
  },
  methods: {
    getFileInfoListFun (value) {
      getFileInfoList(value).then(response => {
        this.fileList = response.map(item => {
          item.url = storage.downloadURL + item.uid
          item.status = 'done'
          return item
        })
      })
    },
    checkFileSize (image) {
      return image.size / 1024 / 1024 < this.fileSize
    },
    checkFileType (image) {
      return image.type.indexOf('image') > -1
    },
    validFileFormer (fileName) {
      var res = fileName.split('.')
      if (fileName.length == 1) {
        return this.accept.indexOf(fileName) > -1
      } else {
        return this.accept.indexOf(res[res.length - 1]) > -1
      }
    },
    validator (fn) {
      const _this = this
      let msg = ''
      if (this.fileList.length == 0) {
        msg = '附件不能为空'
      }
      if (this.fileList.length > this.limit) {
        msg = '附件数量不能大于限定值'
      }
      fn(msg)
    },
    resolveURL () {
      return storage.uploadURL
    },
    FileBeforeUpload (file) {
      this.$emit('FileBeforeUpload', file)
      return new Promise((resolve, reject) => {
        const isLt20M = file.size / 1024 / 1024 < this.fileSize
        if (!isLt20M) {
          this.$notify.error('文件大小不能大于' + this.fileSize + 'MB')
          reject(new Error(false))
        } else if (!!this.accept && !this.validFileFormer(file.name)) {
          this.$notify.error('上传文件格式错误！')
          reject(new Error(false))
        } else {
          if (this.beforeUpload instanceof Function) {
            this.beforeUpload(file, resolve, reject)
          } else {
            resolve()
          }
        }
      })
    },
    handleUploadData (file) {
      if (this.bucketName == '' || this.systemName == '') {
        console.error('bucketName值', this.bucketName)
        console.error('systemName值', this.systemName)
        return
      }
      const data = {
        uid: file.uid,
        md5: '',
        name: file.name,
        chunked: false,
        bucketName: this.bucketName,
        systemName: this.systemName,
        markText: this.markText
      }
      return data
    },
    handleChange (info) {
      let fileList = [...info.fileList]

      if (fileList.length > this.limit) {
        this.$notify.error('超出上传文件最大数量限制')
        return false
      }

      // 2. read from response and show file link
      fileList = fileList.map((file) => {
        const newfile = {
          uid: file.uid,
          name: file.name,
          status: file.status,
          parentId: this.parentId,
          configGroup: this.configGroup,
          url: ''
        }

        if (file.response) {
          // Component will show file.url as link
          if (file.response.code == 0) {
            newfile.url = storage.downloadURL + file.response.data.key
            newfile.uid = file.response.data.key
            newfile.status = 'done'
          } else {
            newfile.status = 'error'
          }
        } else {
          newfile.url = file.url
        }
        return newfile
      })
      this.fileList = fileList

      if (info.file.status === 'done') {
        this.$emit('FileSuccessUpload', info)
        if (this.parentId) {
          this.fileSubmit(this.parentId, fileList, this.configGroup).then(
            (res) => {
              this.$emit('input', fileList, 'over', info)
            }
          )
        }
      }
      this.$emit('input', fileList, info.file.status, info)
    },
    downloadClick (file) {
      if (this.beforeDownload instanceof Function) {
        this.beforeUpload(file)
      } else {
        window.location.href = file.url
      }
    },
    handleFileRemove (info) {
      if (this.handleRemove) {
        return this.handleRemove(info)
      } else {
        return this.handleFileRemoveDefault(info)
      }
    },
    handleFileRemoveDefault (info) {
      return new Promise((resolve, reject) => {
        const _info = info
        // //删除附件关系
        Modal.confirm({
          title: '提示',
          content: '删除将会立即生效,确认删除吗？',
          destroyOnClose: true,
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            if (
              _info.parentId &&
              _info.uid != '' &&
              _info.configGroup != ''
            ) {
              const options = {
                businessId: _info.parentId,
                fileId: _info.uid,
                fileType: _info.configGroup
              }
              deleteFile(options).then((response) => {
                this.getFileList()
                resolve(true)
              })
            } else {
              resolve(true)
            }
          },
          onCancel () {
            resolve(false)
          }
        })
      })
    },
    fileSubmit (parentId, fileList, configGroup) {
      const ff = []
      fileList.map(function (val) {
        const up = {
          uid: val.uid,
          name: val.name,
          parentId: parentId,
          businessType: 'mb',
          configGroup: configGroup
        }
        ff.push(up)
      })
      const options = {
        parentId: parentId,
        configGroup: configGroup,
        list: ff
      }
      return saveFile(options)
    },
    getFileList () {
      const options = {
        businessId: this.parentId,
        fileType: this.configGroup
      }
      if (!this.parentId) {
        return false
      }
      getFileList(options).then(
        (response) => {
          let arrlist = response
          arrlist = arrlist.map((arrData) => {
            const newfile = {
              uid: arrData.fileId,
              name: arrData.fileName,
              status: 'done',
              parentId: arrData.businessId,
              configGroup: arrData.fileType,
              url: storage.downloadURL + arrData.fileId
            }
            return newfile
          })
          this.fileList = arrlist
          this.$emit('input', arrlist)
        })
    }
  }
}
</script>
